﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SSISLib
{
    public partial class SharePointListConfigForm : Form
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public SharePointListConfigForm(System.Collections.Hashtable properties, bool bWriteMode, string portID, BlueIntegrator.DAL.DALBase dal, string[] tokens = null)
        {
            InitializeComponent();
            m_bWriteMode = bWriteMode;
            m_properties = properties;
            m_portId = portID;
            m_dal = dal;
            m_tokens = tokens;

            int nBindings = SafeGetInt(properties["NumTBindings"]);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bf.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
            bf.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded;

            for (int i=0; i < nBindings; i++)
            {
                string bindingInfo = properties["Binding:" + i] as string;

                if (bindingInfo != null)
                {
                    SharePointListAPI.Binding b = (SharePointListAPI.Binding)bf.Deserialize(new System.IO.MemoryStream(System.Convert.FromBase64String(bindingInfo)));
                    m_bindings.Add(b);
                }
            }

            m_mode = (SharePointListAPI.UpdateMode)SafeGetInt(properties["SPMode"]);

            this.userTextBox.Text = properties["SPUser"] as string ?? "";
            this.urlTextBox.Text = properties["SPURL"] as string ?? "";
            this.orgTextBox.Text = properties["SPList"] as string ?? "";
            this.pwdTextBox.Text = BlueIntegrator.Helpers.Encryption.DecryptString(properties["SPPwd"] as string ?? "", "SSIS");
            this.timeoutTextBox.Text = SafeGetInt(properties["SPTimeOut"], 100).ToString();

            if (!m_bWriteMode)
            {
                try
                {
                    if (m_properties["CAMLQuery"] != null)
                        this.camlTextBox.Text = m_properties["CAMLQuery"].ToString();
                }
                catch
                {
                }
            }
            else
            {
                this.tabControl1.TabPages.Remove(this.camlTabPage);
            }

            if (m_bWriteMode)
            {
                this.tabControl1.TabPages.Remove(this.sourceTabPage);
                this.modeComboBox.SelectedIndex = 0;

                try
                {
                    this.modeComboBox.SelectedIndex = (int)m_mode + 1;
                }
                catch
                {
                }
            }
            else
            {
                this.modeLabel.Visible = this.modeLabel2.Visible = this.modeComboBox.Visible = false;
            }
        }

        /// <summary>
        /// Conversion helper
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        private int SafeGetInt(object v)
        {
            return SafeGetInt(v, 0);
        }

        /// <summary>
        /// Conversion helper
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        private int SafeGetInt(object v, int def)
        {
            if (v == null)
                return def;
            
            try
            {
                return System.Convert.ToInt32(v);
            }
            catch
            {
            }

            return def;
        }

        /// <summary>
        /// Property helper
        /// </summary>
        /// <param name="propname"></param>
        /// <returns></returns>
        private object GetPropertyHelper(string propname)
        {
            object val = m_properties[propname];
            return val ?? "";
        }

        /// <summary>
        /// Property helper
        /// </summary>
        /// <param name="propname"></param>
        /// <returns></returns>
        private void SetPropertyHelper(string propname, object val)
        {
            m_properties[propname] = val;
        }

        bool m_bWriteMode;
        List<SharePointListAPI.Binding> m_bindings = new List<SharePointListAPI.Binding>();
        SharePointListAPI.UpdateMode m_mode = SharePointListAPI.UpdateMode.Upsert;
        TabPage m_previousTab = null;
        bool m_bLookup = false;
        System.Collections.Hashtable m_properties = null;
        string m_portId;
        BlueIntegrator.DAL.DALBase m_dal = null;
        string[] m_tokens = null;

        /// <summary>
        /// Cancel handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Validate and save
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (modeComboBox.SelectedIndex == 0 && m_bWriteMode)
                {
                    MessageBox.Show("You must select a mode.", "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    this.modeComboBox.Focus();
                    this.tabControl1.SelectedIndex = 0;
                    return;
                }

                if (this.urlTextBox.Text == "")
                {
                    MessageBox.Show("You must enter a SharePoint server URL.", "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    this.urlTextBox.Focus();
                    this.tabControl1.SelectedIndex = 0;
                    return;
                }

                SharePointListAPI api = new SharePointListAPI();

                if (this.timeoutTextBox.Text == "")
                    this.timeoutTextBox.Text = "60";

                int timeOut;

                if (!int.TryParse(this.timeoutTextBox.Text, out timeOut))
                {
                    this.timeoutTextBox.Text = "60";
                }

                try
                {
                    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                    api.GetColumns(this.orgTextBox.Text, this.urlTextBox.Text, this.userTextBox.Text, this.pwdTextBox.Text, timeOut, m_dal);
                }
                catch (System.Exception exc)
                {
                    MessageBox.Show("An error occurred connecting to the SharePoint server : " + exc.ToString() + "\r\n\r\nPlease check the connection parameters.", "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    this.urlTextBox.Focus();
                    this.tabControl1.SelectedIndex = 0;
                    return;
                }
                finally
                {
                    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                }

                List<SharePointListAPI.Binding> result = new List<SharePointListAPI.Binding>();
                string bindStr = "\\";

                if (this.dataFieldsListView.Items.Count == 0)
                {
                    result.AddRange(m_bindings);
                    bindStr = m_properties["SPRelevantColumns"] as string;
                }
                else
                foreach (ListViewItem lvi in this.dataFieldsListView.Items)
                {
                    if (lvi.Text == "{Attachments}")
                    {
                        m_properties["ReadAttachments"] = lvi.Checked;
                        continue;
                    }

                    if (lvi.Checked || lvi.SubItems[3].Text != "<None>")
                    {
                        SharePointListAPI.Binding binding = new SharePointListAPI.Binding();
                        binding.columnName = lvi.Text;
                        binding.targetName = lvi.SubItems[1].Text;
                        binding.bKey = lvi.SubItems[3].Text != "<None>";
                        binding.binding = lvi.SubItems[3].Text != "<None>" ? lvi.SubItems[3].Text : null;
                        bindStr += lvi.Text + "\\";

                        if (lvi.Tag is string)
                            binding.ssisType = lvi.Tag as string;
                        else
                            binding.ssisType = ((KeyValuePair<string, string>)lvi.Tag).Value;

                        result.Add(binding);
                    }
                }

                m_properties["SPMode"] = (SharePointListAPI.UpdateMode)this.modeComboBox.SelectedIndex - 1;
                m_properties["SPURL"] = this.urlTextBox.Text;
                m_properties["SPList"] = this.orgTextBox.Text;
                m_properties["SPUser"] = this.userTextBox.Text;
                m_properties["SPPwd"] = BlueIntegrator.Helpers.Encryption.EncryptString(this.pwdTextBox.Text, "SSIS");
                m_properties["SPRelevantColumns"] = bindStr;

                if (!int.TryParse(this.timeoutTextBox.Text, out timeOut))
                    timeOut = 60;

                m_properties["SPTimeOut"] = timeOut;
                m_properties["NumTBindings"] = result.Count;

                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                bf.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
                bf.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded;

                for (int i = 0; i < result.Count; i++)
                {
                    System.IO.MemoryStream str = new System.IO.MemoryStream();
                    bf.Serialize(str, result[i]);
                    m_properties["Binding:" + i] = System.Convert.ToBase64String(str.ToArray());
                }

                if (!m_bWriteMode)
                {
                    if (this.camlTextBox.Text.Trim() != "")
                    {
                        try
                        {
                            System.Xml.XmlDocument camlDoc = new System.Xml.XmlDocument();
                            camlDoc.LoadXml(this.camlTextBox.Text);

                            if (camlDoc.DocumentElement.LocalName != "Query")
                            {
                                MessageBox.Show("Error - invalid CAML query", "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                this.tabControl1.SelectedTab = this.camlTabPage;
                                this.camlTextBox.Focus();
                                return;
                            }
                        }
                        catch
                        {
                            MessageBox.Show("Error - invalid CAML query", "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            this.tabControl1.SelectedTab = this.camlTabPage;
                            this.camlTextBox.Focus();
                            return;
                        }
                    }

                    try
                    {
                        m_properties["CAMLQuery"] = this.camlTextBox.Text.Trim();
                    }
                    catch
                    {
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (System.Exception exc)
            {
                MessageBox.Show("Error : " + exc.ToString(), "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        /// <summary>
        /// Initialisation on tab change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                if (m_previousTab == this.connectionTab)
                {
                    this.dataFieldsListView.Items.Clear();
                }

                if (this.tabControl1.SelectedTab != this.connectionTab)
                {
                    int timeOut;

                    if (!int.TryParse(this.timeoutTextBox.Text, out timeOut))
                    {
                        timeOut = 60;
                    }

                    if (m_bWriteMode)
                    {
                        SharePointListAPI api = new SharePointListAPI();
                        KeyValuePair<string, string>[] columns = null;
                        try
                        {
                            columns = api.GetColumns(this.orgTextBox.Text, this.urlTextBox.Text, this.userTextBox.Text, this.pwdTextBox.Text, timeOut, m_dal);
                        }
                        catch (System.Exception exc)
                        {
                            MessageBox.Show("An error occurred connecting to the SharePoint server : " + exc.ToString() + "\r\n\r\nPlease check the connection parameters.", "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            this.urlTextBox.Focus();
                            this.tabControl1.SelectedIndex = 0;
                            return;
                        }
                    }
                    else if (this.dataFieldsListView.Items.Count == 0)
                    {
                        SharePointListAPI api = new SharePointListAPI();
                        KeyValuePair<string, string>[] columns = null;
                        try
                        {
                            columns = api.GetColumns(this.orgTextBox.Text, this.urlTextBox.Text, this.userTextBox.Text, this.pwdTextBox.Text, timeOut, m_dal);
                        }
                        catch (System.Exception exc)
                        {
                            MessageBox.Show("An error occurred connecting to the SharePoint server : " + exc.ToString() + "\r\n\r\nPlease check the connection parameters.", "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            this.urlTextBox.Focus();
                            this.tabControl1.SelectedIndex = 0;
                            return;
                        }

                        this.dataFieldsListView.Items.Clear();

                        // load columns...
                        foreach (KeyValuePair<string, string> column in columns)
                        {
                            ListViewItem lvi = this.dataFieldsListView.Items.Add(column.Key);
                            lvi.Tag = column.Value;

                            bool bChecked = false;
                            string filter = "<None>";

                            foreach (SharePointListAPI.Binding bd in m_bindings)
                            {
                                if (bd.columnName == column.Key)
                                {
                                    bChecked = true;
                                    filter = bd.binding;
                                    lvi.SubItems.Add(bd.TargetName);
                                    break;
                                }
                            }

                            if (!bChecked)
                            {
                                lvi.SubItems.Add(column.Key);
                            }

                            lvi.SubItems.Add(column.Value);
                            lvi.Checked = bChecked;
                            lvi.SubItems.Add(filter ?? "<None>");
                        }

                        // add attachments
                        ListViewItem lvia = this.dataFieldsListView.Items.Add("{Attachments}");
                        lvia.Tag = "{Attachments}";
                        lvia.Checked = BlueIntegrator.Helpers.Conversion.ConvertToBool(m_properties["ReadAttachments"]);
                        lvia.SubItems.Add("");
                        lvia.SubItems.Add("");
                        lvia.SubItems.Add("");
                        lvia.SubItems.Add("");
                    }
                }
            }
            catch (System.Exception exc)
            {
                MessageBox.Show("Error : " + exc.ToString(), "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            }

            m_previousTab = this.tabControl1.SelectedTab;
        }

        /// <summary>
        /// List change handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataFieldsListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.filterLabel.Enabled = this.filterComboBox.Enabled = this.filterButton.Enabled = (this.dataFieldsListView.SelectedIndices.Count == 1 && this.dataFieldsListView.SelectedItems[0].Text != "{Attachments}");
            if (this.filterComboBox.Enabled)
            {
                this.filterComboBox.Text = this.dataFieldsListView.SelectedItems[0].SubItems[3].Text;
            }
        }

        private void SharePointConfigForm_Load(object sender, EventArgs e)
        {
            this.urlTextBox.Focus();
        }

        /// <summary>
        /// Filter click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void filterButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.dataFieldsListView.SelectedItems[0].SubItems[3].Text = this.filterComboBox.Text;
            }
            catch
            {
            }
        }

        /// <summary>
        /// help handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void helpButton_Click(object sender, EventArgs e)
        {
            if (m_bWriteMode)
            {
                System.Diagnostics.Process.Start("http://BlueIntegrator.com/Index.Aspx?PageId=SharePointDestinationComponent");
            }
            else
            {
                System.Diagnostics.Process.Start("http://BlueIntegrator.com/Index.Aspx?PageId=SharePointSourceComponent");
            }
        }

        /// <summary>
        /// Schema generation...
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                CRMEtc.PromptSchemaName psn = new CRMEtc.PromptSchemaName(this.urlTextBox.Text + " : " + this.orgTextBox.Text);

                string schId = System.Guid.NewGuid().ToString();

                if (psn.ShowDialog() == DialogResult.OK)
                {
                    foreach (KeyValuePair<string, string> s in m_dal.EnumAllSchemaIdsAndNames())
                    {
                        if (s.Value.ToUpper() == psn.textBox1.Text.ToUpper())
                        {
                            schId = s.Key;
                        }
                    }

                    // now generate the schema
                    System.Xml.Schema.XmlSchema sch = new System.Xml.Schema.XmlSchema();

                    // add root element
                    System.Xml.Schema.XmlSchemaElement root = new System.Xml.Schema.XmlSchemaElement();
                    root.Name = "BlueIntegratorSharePoint";

                    // add complex type
                    System.Xml.Schema.XmlSchemaComplexType rootct = new System.Xml.Schema.XmlSchemaComplexType();
                    rootct.Particle = new System.Xml.Schema.XmlSchemaSequence();
                    root.SchemaType = rootct;

                    // add record
                    System.Xml.Schema.XmlSchemaElement recordEl = new System.Xml.Schema.XmlSchemaElement();
                    recordEl.Name = "Record";
                    (rootct.Particle as System.Xml.Schema.XmlSchemaSequence).Items.Add(recordEl);
                    recordEl.MinOccurs = 0;
                    recordEl.MaxOccurs = int.MaxValue;
                    System.Xml.Schema.XmlSchemaComplexType recct = new System.Xml.Schema.XmlSchemaComplexType();
                    recct.Particle = new System.Xml.Schema.XmlSchemaSequence();

                    recordEl.SchemaType = recct;

                    // add attributes
                    foreach (ListViewItem lvi in this.dataFieldsListView.Items)
                    {
                        if (lvi.Text != "{Attachments}")
                        {
                            System.Xml.Schema.XmlSchemaAttribute attr = new System.Xml.Schema.XmlSchemaAttribute();
                            attr.Name = lvi.Text;
                            attr.Use = System.Xml.Schema.XmlSchemaUse.Optional;
                            recct.Attributes.Add(attr);
                        }
                    }

                    // add Action element
                    System.Xml.Schema.XmlSchemaElement actionEl = new System.Xml.Schema.XmlSchemaElement();
                    actionEl.Name = "Action";
                    actionEl.MinOccurs = 0;
                    actionEl.MaxOccurs = 1;
                    (recct.Particle as System.Xml.Schema.XmlSchemaSequence).Items.Add(actionEl);

                    System.Xml.Schema.XmlSchemaAttribute actionAttr = new System.Xml.Schema.XmlSchemaAttribute();
                    actionAttr.Name = "ActionType";
                    System.Xml.Schema.XmlSchemaSimpleType st = new System.Xml.Schema.XmlSchemaSimpleType();
                    actionAttr.SchemaType = st;
                    st.Content = new System.Xml.Schema.XmlSchemaSimpleTypeRestriction();
                    (st.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).BaseTypeName = new System.Xml.XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
                    (st.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets.Add(new System.Xml.Schema.XmlSchemaEnumerationFacet() { Value = "Insert" });
                    (st.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets.Add(new System.Xml.Schema.XmlSchemaEnumerationFacet() { Value = "Update" });
                    (st.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets.Add(new System.Xml.Schema.XmlSchemaEnumerationFacet() { Value = "Delete" });
                    (st.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets.Add(new System.Xml.Schema.XmlSchemaEnumerationFacet() { Value = "Upsert" });
                    
                    System.Xml.Schema.XmlSchemaComplexType actct = new System.Xml.Schema.XmlSchemaComplexType();
                    actct.Particle = new System.Xml.Schema.XmlSchemaSequence();

                    actionEl.SchemaType = actct;
                    actct.Attributes.Add(actionAttr);

                    // add Key element
                    System.Xml.Schema.XmlSchemaElement keyEl = new System.Xml.Schema.XmlSchemaElement();
                    keyEl.Name = "Key";
                    keyEl.MinOccurs = 0;
                    keyEl.MaxOccurs = 1;
                    (actct.Particle as System.Xml.Schema.XmlSchemaSequence).Items.Add(keyEl);

                    System.Xml.Schema.XmlSchemaComplexType keyct = new System.Xml.Schema.XmlSchemaComplexType();
                    keyEl.SchemaType = keyct;

                    // add attributes
                    foreach (ListViewItem lvi in this.dataFieldsListView.Items)
                    {
                        if (lvi.Text != "{Attachments}")
                        {
                            System.Xml.Schema.XmlSchemaAttribute attr = new System.Xml.Schema.XmlSchemaAttribute();
                            attr.Name = lvi.Text;
                            attr.Use = System.Xml.Schema.XmlSchemaUse.Optional;
                            keyct.Attributes.Add(attr);
                        }
                    }

                    // add content element
                    System.Xml.Schema.XmlSchemaElement attachmentEl = new System.Xml.Schema.XmlSchemaElement();
                    attachmentEl.Name = "Attachment";
                    attachmentEl.MinOccurs = 0;
                    attachmentEl.MaxOccurs = int.MaxValue;
                    (recct.Particle as System.Xml.Schema.XmlSchemaSequence).Items.Add(attachmentEl);

                    System.Xml.Schema.XmlSchemaAttribute attachmentElAttr = new System.Xml.Schema.XmlSchemaAttribute();
                    attachmentElAttr.Name = "AttachmentName";
                    System.Xml.Schema.XmlSchemaComplexType attct = new System.Xml.Schema.XmlSchemaComplexType();
                    attct.Particle = new System.Xml.Schema.XmlSchemaSequence();

                    attachmentEl.SchemaType = attct;
                    attct.Attributes.Add(attachmentElAttr);

                    System.Xml.Schema.XmlSchemaElement base64El = new System.Xml.Schema.XmlSchemaElement();
                    base64El.Name = "Base64Content";
                    base64El.MinOccurs = 0;  base64El.MaxOccurs = 1;
                    (attct.Particle as System.Xml.Schema.XmlSchemaSequence).Items.Add(base64El);

                    System.Xml.Schema.XmlSchemaAttribute attachmentActionAttr = new System.Xml.Schema.XmlSchemaAttribute();
                    attachmentActionAttr.Name = "AttachmentActionType";
                    System.Xml.Schema.XmlSchemaSimpleType ast = new System.Xml.Schema.XmlSchemaSimpleType();
                    attachmentActionAttr.SchemaType = ast;
                    ast.Content = new System.Xml.Schema.XmlSchemaSimpleTypeRestriction();
                    (ast.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).BaseTypeName = new System.Xml.XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
                    (ast.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets.Add(new System.Xml.Schema.XmlSchemaEnumerationFacet() { Value = "Insert" });
                    (ast.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets.Add(new System.Xml.Schema.XmlSchemaEnumerationFacet() { Value = "Update" });
                    (ast.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets.Add(new System.Xml.Schema.XmlSchemaEnumerationFacet() { Value = "Delete" });
                    (ast.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets.Add(new System.Xml.Schema.XmlSchemaEnumerationFacet() { Value = "Upsert" });
                    attct.Attributes.Add(attachmentActionAttr);

                    sch.Items.Add(root);

                    // get XSD
                    System.IO.StringWriter sw = new System.IO.StringWriter();
                    sch.Write(sw);

                    // save schema to DAL
                    ///////////////////////
                    m_dal.SaveSchema(schId, sw.ToString(), new BlueIntegrator.DAL.SchemaAuxiliaryProperties());
                    m_dal.RenameSchema(schId, psn.textBox1.Text);

#if DEBUG
                    MessageBox.Show(sw.ToString());
#endif
                }
            }
            catch (System.Exception exc)
            {
                MessageBox.Show("Error : " + exc.ToString(), "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        /// <summary>
        /// CAML token
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void camlTokenLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            BlueIntegrator.Messaging.SelectToken selTok = new BlueIntegrator.Messaging.SelectToken(m_tokens, false);

            if (selTok.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                int m_pos = 0;

                //if (this.conditionTextBox.Focused)
                {
                    m_pos = this.camlTextBox.SelectionStart;
                }

                if (this.camlTextBox.SelectionStart != m_pos)
                {
                    this.camlTextBox.SelectionStart = m_pos;
                    this.camlTextBox.SelectionLength = 0;
                }
                this.camlTextBox.SelectedText = "%" + selTok.ResultToken + "%";
                this.camlTextBox.Focus();
            }
        }
    }
}
